package com.hongtong.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongtong.auto.JSONAuthentication;
import com.hongtong.entity.TeUser;
import com.hongtong.mapper.TeUserMapper;
import com.hongtong.response.Result;
import com.hongtong.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hongtong
 * @since 2022-04-12
 */
@RestController
@RequestMapping("/te-user")
public class TeUserController extends JSONAuthentication {
    @Autowired
    TeUserMapper teUserMapper;
    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password1, @RequestParam("role") String role) throws  Exception{
        TeUser user=new TeUser();
        user.setUsername(username);
        user.setPassword(password1);
        user.setRole(role);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("username",user.getUsername());
        TeUser a= teUserMapper.selectOne(wrapper);
        if(a!=null){
            Result result= Result.error();
            result.setMessage("该用户已存在");
            this.WriteJSON(request, response, result);
        }else {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            user.setPicture(avatar_url);
            response.reset();
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            String password= new BCryptPasswordEncoder().encode(user.getPassword());
            user.setPassword(password);
            System.out.println(password);
            int i=teUserMapper.insert(user);
            if(i>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }

    }

    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId ) throws Exception{
        int i=teUserMapper.deleteById(userId);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/updPassword")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("password") String password,@RequestParam("rpassword") String rpassword,@RequestParam("id") int id )throws Exception{
        TeUser shUser=teUserMapper.selectById(id);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if(encoder.matches(password,shUser.getPassword())){
            String newPassword=new BCryptPasswordEncoder().encode(rpassword);
            shUser.setPassword(newPassword);
            if(teUserMapper.updateById(shUser)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }else{
            Result error = Result.error();
            error.setMessage("密码不正确");
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "通过用户名查找用户")
    @PostMapping("/findByName")
    public void findById(HttpServletRequest request, HttpServletResponse response,@RequestParam("username") String  username,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{

        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("username",username);
        Page<TeUser> shUserPage=new Page<>(current,size);
        Page<TeUser> shUserPages=teUserMapper.selectPage(shUserPage,wrapper);
        List<TeUser> records = shUserPages.getRecords();
        int total=teUserMapper.selectCount(wrapper);
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有用户")
    @PostMapping("/findAllUser")
    public void findByIda(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        Page<TeUser> shUserPage=new Page<>(current,size);
        Page<TeUser> shUserPages=teUserMapper.selectPage(shUserPage,null);
        List<TeUser> records = shUserPages.getRecords();
        int total=teUserMapper.selectCount(null);
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "通过id查找用户")
    @PostMapping("/findByUserId")
    public void findByUserId(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int  id)throws  Exception{
        TeUser shUser=teUserMapper.selectById(id);
        if(shUser!=null){
            Result ok = Result.ok().data("user",shUser);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

}

